package com.api.controller

import com.api.config.APIConfig
import com.api.util.TokenUtils
import com.base.db.mysql.admin_getUserInfoByUID
import com.base.db.mysql.app_getUserInfoByUID
import com.base.db.mysql.service_getUserInfoByUID
import com.base.db.redis.cache_addCode_pic
import com.base.db.redis.cache_addToken_refresh
import com.base.model.api.APIFrom
import com.base.utils.ULID
import com.yfree.model.YModel
import com.yfree.utils.YMD5Utils
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import java.io.ByteArrayOutputStream
import javax.imageio.ImageIO
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

fun Controller_API.doCode(request: HttpServletRequest, response: HttpServletResponse) {
    val loginname = request.getParameter("loginname")
    if (loginname.isNullOrEmpty()) {
        response.outputStream.write("loginname为空".toByteArray())
        response.outputStream.flush()
        response.outputStream.close()
        return
    }
    val createText = defaultKaptcha.createText()
    if (!redisService.cache_addCode_pic(this, loginname, createText)) return
    val jpegOutputStream = ByteArrayOutputStream()
    ImageIO.write(defaultKaptcha.createImage(createText), "jpg", jpegOutputStream)
    response.setHeader("Cache-Control", "no-store")
    response.setHeader("Pragma", "no-cache")
    response.setDateHeader("Expires", 0)
    response.contentType = "image/jpeg"
    response.outputStream.write(jpegOutputStream.toByteArray())
    response.outputStream.flush()
    response.outputStream.close()
}

fun Controller_API._getUserModelByUID(uid: String, from: APIFrom): YModel {
    val accessToken = TokenUtils.encode(uid)
    val refreshToken_new = ULID().nextULID()
    redisService.cache_addToken_refresh(from, refreshToken_new, uid)
    when (from) {
        APIFrom.App -> {
            val userModel = mysqlService.app_getUserInfoByUID(uid)!!
            userModel.name = if (userModel.name.isNullOrEmpty()) APIConfig.default_name else userModel.name
            userModel.avatar = if (userModel.avatar.isNullOrEmpty()) APIConfig.default_avatar else userModel.avatar
            userModel.sign = "${accessToken}|${refreshToken_new}"
            return userModel
        }

        APIFrom.Admin -> {
            val userModel = mysqlService.admin_getUserInfoByUID(uid)!!
            userModel.name = if (userModel.name.isNullOrEmpty()) APIConfig.default_name else userModel.name
            userModel.avatar = APIConfig.default_avatar
            userModel.sign = "${accessToken}|${refreshToken_new}"
            return userModel
        }

        APIFrom.Service -> {
            val userModel = mysqlService.service_getUserInfoByUID(uid)!!
            userModel.name = if (userModel.name.isNullOrEmpty()) APIConfig.default_name else userModel.name
            userModel.avatar = if (userModel.avatar.isNullOrEmpty()) APIConfig.default_avatar else userModel.avatar
            userModel.sign = "${accessToken}|${refreshToken_new}"
            return userModel
        }
    }
}

private fun Controller_API._getAttr(key: String): String? {
    val attributes = (RequestContextHolder.getRequestAttributes() as ServletRequestAttributes).request.getAttribute(APIConfig.attrKey) as? Map<*, *>
    return attributes?.get(key)?.toString()
}

fun Controller_API._getUID() = _getAttr("uid")
fun Controller_API._getRefreshToken() = _getAttr("refreshToken")

fun Controller_API.encodePassword(password: String): String {
    return YMD5Utils.getMD5("${YMD5Utils.getMD5(password)}${APIConfig.md5Key}")
}